﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Configuration;

namespace KhoaLuan.ProcessAJAX
{
    /// <summary>
    /// Summary description for AJAXImport
    /// </summary>
    public class AJAXImport : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var httpPostedFile = context.Request.Files["File"];
                var tablename = context.Request.Form["TableName"];
                if (httpPostedFile != null)
                {
                  //  string filename = "~/Images/Uploads/" + DateTime.Now.ToString("ddMMyyyyhhmmss") + httpPostedFile.FileName;
                   // httpPostedFile.SaveAs(string.Concat(HttpContext.Current.Server.MapPath("~/Temp/" + httpPostedFile.FileName)));
                    string filename = string.Concat(HttpContext.Current.Server.MapPath("~/Temp/" + httpPostedFile.FileName));
                    httpPostedFile.SaveAs(filename);
                    //da import thanh cong, xu ly import o day

                    string excelConString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", filename);

                    OleDbConnection connection = new OleDbConnection();
                    connection.ConnectionString = excelConString;
                    OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
                    connection.Open();
                    OleDbDataReader dr = command.ExecuteReader();
                    string sqlconString = ConfigurationManager.ConnectionStrings["HocSinhstr"].ConnectionString;
                    SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlconString);
                    bulkInsert.DestinationTableName = tablename;
                    bulkInsert.WriteToServer(dr);
                    context.Response.Write(new JavaScriptSerializer().Serialize(new { Status = "Success", Location = filename }));
                }
                else
                {
                    context.Response.Write(new JavaScriptSerializer().Serialize(new { Status = "Error" }));
                }
            }
            catch (Exception)
            {
                context.Response.Write(new JavaScriptSerializer().Serialize(new { Status = "Error" }));

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}